<template>
	<view class="box">
		<!-- 选择会员 -->
		<view class="selectMember">
			<view class="member">
				<text style="position: relative;">{{start_date || '日期：'}}
					<picker mode="date" :start="start" :end="end"  @change="bindDateChange" v-if="!selected" style="position: absolute;left:0;top: 0;width: 100%;height: 100%;">
					</picker> 
				</text>
			</view>
			<view class="save" @click=" showModalbtn(4)" v-if="selected != 1">保存</view>
			<view class="toSend" @click="selected != 1 ? showModalbtn(2) : ''" >申请评估</view>
		</view>
		
		<view class="content">
			<view class="question" v-for="(item,index) in psychologyQuestion" :key="index">
				<view class="title">
					<text>{{index < 9 ? '0'+ Number(index+1) : Number(index+1)}}</text>
					<view>{{item.name}}</view>
				</view>
				<view v-if="item.adTopicsRepliesEntityList == false">
					<view class="entry" v-if="item.id == 220">
						<input type="number" :disabled="selected == 1" placeholder="收缩压" class="systolicPressure" v-model="systolic" @blur="systolicInput(systolic,name='systolicPressure',index= index)">|<input type="number" :disabled="selected == 1" placeholder="舒张压" v-model="diastolic" @blur="systolicInput(diastolic,name='diastolicPressure',index= index)" class="diastolicPressure">
					</view>
					<view class="entry" v-else>
						<input type="number" :disabled="selected == 1" v-model="inputRecord[index]" @blur="systolicInput(inputRecord[index],name='pressure'+index,index)" :placeholder="item.id == 222 ? 'BMI（体重指数）' : item.id == 223 ? '0-5000': item.id == 224 ? '0-7': item.id == 226 ? '年龄':item.id == 235 ? '0-7' :'0-300'">
					</view>
				</view>
				<view v-else>
					<view class="option" v-for="(bitem,bindex) in item.adTopicsRepliesEntityList" :key="bindex">
						<view @click="answer(item,bitem)">
							<text>{{bitem.elections}}、{{bitem.value}}</text> 
							<image src="@/static/img/select@2x.png"  v-if="bitem.checked == false"></image>  
							<image src="@/static/img/selected@2x.png" v-else></image>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {getUrlParam} from '@/static/js/filter.js'
	export default {
		data () {
			const currentDate = this.getDate({
				format: true
			})
			return {
				start:'',
				end:currentDate,
				start_date:'',
				selected:'', //申请评估进来的状态
				psychologyQuestion:{},
				systolic:null, //收缩压
				diastolic:'', //舒张压
				inputRecord:{},//所有输入框的数据
				id:'',
				selected:''
			}
		},
		created() {
			const _this = this;
			_this.id = getUrlParam('id');
			_this.selected = getUrlParam('selected');
			_this.questionArr().then((response) => {
				if(response) {
					if(_this.id) {
						_this.$api.appSicknessDangeDetail(_this.id).then((res) => {
							if(res.data.returnCode == 200) {
								const data1 = res.data.result;
								const data2 = res.data.result && res.data.result.userTopicsEntities;
								_this.userId = data1.userId;
								_this.healthId = data1.healthId;
								_this.start_date = data1.fillFormDate;
								_this.editTid = data1.tid;
								_this.psychologyQuestion.map((a) => {
									data2.map((b,bi) => {
										if(a.id == b.titleId) {
											a.nid = b.id
											if(b.titleId == 220) {
												_this.systolic = b.userValue.split('/')[0];
												_this.diastolic = b.userValue.split('/')[1];
											}else if(b.userOption) {
												a.adTopicsRepliesEntityList != false && a.adTopicsRepliesEntityList.map((c) => {
													c.nid = b.id;											
													if(b.userOption == c.elections) {
														c.checked = true;
													}
												})
											}else {
												_this.inputRecord[bi] = b.userValue;
											}								
										}
									})
								})
							}
						})
					}
					
				}
			})
		},
		methods:{
			//input框限制输入
			systolicInput(e,v,i) {	
				var reg = /^-?\d+$/;
				var reg1 = /^(300|[1-9]?\d(\.\d)?)$/;
				var reg2 = /^(\d|[1-9]\d|300)(\.\d{1,2})?$/;
				if(v == 'systolicPressure') {
					if(reg.test(this.systolic)) {
						if (this.systolic>300) {
						  this.systolic = 300;
						} else if (this.systolic<0 ) {
						  this.systolic = 0;						  
						}
					}else {
						this.systolic = 0;
					}
				}else if(v == 'diastolicPressure') {
					if(reg.test(this.diastolic)) {
						if(this.diastolic>300) {
							this.diastolic = 300
						}else if(this.diastolic < 0) {
							this.diastolic = 0
						}
					}else {
						this.diastolic = 0
					}
				}else if(v == 'pressure2') {
					if (reg1.test(e)) {				
						this.inputRecord[i] = e
					} else {
						if(e > 300) {
							this.inputRecolrd[i] = 300
						}else if(e < 0) {						
							this.inputRecord[i] = 0
						}else {
							setTimeout(() => {
								this.inputRecord[i] = this.inputRecord[i].substring(0,this.inputRecord[i].indexOf(".")+3);
								this.$forceUpdate()
							},50)
						}			
					}
				}else if(v == 'pressure6') {
					if(reg.test(e)) {
						if(e > 300) {
							this.inputRecord[i] = 300
						}else if(e < 0) {
							this.inputRecord[i] = 0
						}
					}else {
						this.inputRecord[i] = ''
					}
				}else if(v == 'pressure4' || v == 'pressure15') {
					if(reg.test(e)) {
						if(e > 7) {
							this.inputRecord[i] = 7
						}else if(e < 0) {
							this.inputRecord[i] = 0
						}
					}else {
						this.inputRecord[i] = ''
					}
				}else if(v == 'pressure10' || v == 'pressure9' || v == 'pressure11') {
					if(reg2.test(e)) {
						this.inputRecord[i] = e;
					}else {
						if(e > 300) {
							this.inputRecord[i] = 300
						}else if(e < 0) {
							this.inputRecord[i] = 0
						}else {		
							setTimeout(() => {
								this.inputRecord[i] = this.inputRecord[i].substring(0,this.inputRecord[i].indexOf(".")+3);
								this.$forceUpdate()
							},50)
							
						}
					}
				}else if(v == 'pressure3') {
					if(reg.test(e)) {
						if(e >5000) {
							this.inputRecord[i] = 5000
						}else if(e < 0) {
							this.inputRecord[i] = 0
						}
					}else {
						this.inputRecord[i] = ''
					}
				}
				setTimeout(() => {
					this.$forceUpdate()
				},500)
			},
			answer(item,bitem) {
				if(this.selected == 1) {
					return 
				}
				item.adTopicsRepliesEntityList.map((a) => {
					return a.checked = false
				})
				bitem.checked = true
			},
			showModalbtn(e) {
				const _this = this;
				if(! this.start_date) {
					uni.showToast({
						title:'请选择日期',
						icon:'none'
					})
					return 
				}	
				//过滤传给后台的数据
				let appUserTopicsEntities = []			
				_this.psychologyQuestion.map((a,ai) => {
					const bresult = a.adTopicsRepliesEntityList != false && a.adTopicsRepliesEntityList.filter((b) => {
						return b.checked
					}); 
					a.aresult = bresult || _this.inputRecord[ai];
					appUserTopicsEntities.push({
						id:bresult.length > 0 && bresult[0].nid || a.nid,
						titleId: a.id,
						type: a.type,
						userNumber: bresult.length > 0 ? bresult[0].numbers : '',
						userOption:bresult.length > 0 ? bresult[0].elections : '',
						userValue: bresult.length > 0 ? bresult[0].value : '' || _this.inputRecord[ai]		
					})
				})
				appUserTopicsEntities[0].userValue = _this.systolic && _this.systolic +'/'+_this.diastolic; //拼接收缩压与舒张压的数据
				//过滤是否有未选中的
				if(!_this.systolic || !_this.diastolic) {
					uni.showToast({
						title:'请输入您测量的收缩压和舒张压是多少（mmHg）？',
						icon:'none'
					})
					return 
				}			
				var emptyArr = []
				_this.psychologyQuestion.map((a) => {
					if(!a.aresult || a.aresult.length <= 0){
						emptyArr.push(a)
					}
				})
				if(emptyArr.length >= 2) {
					uni.showToast({
						title:emptyArr[1].name,
						icon:'none'
					})
					return 
				}
				const record = {
					appUserTopicsEntities: appUserTopicsEntities,
					appUserTopicsTitleEntity: {
						healthId: localStorage.getItem('userInfo') && JSON.parse(localStorage.getItem('userInfo')).healthId ||'',
						userId: localStorage.getItem('userInfo') && JSON.parse(localStorage.getItem('userInfo')).userId || '',
					},
					fillFormDate: this.start_date,
					source:1,
					status:e,
					title:42,
					type:8,
					userHealthId: localStorage.getItem('userInfo') && JSON.parse(localStorage.getItem('userInfo')).healthId ||'',
					userHealthName:localStorage.getItem('userInfo') && JSON.parse(localStorage.getItem('userInfo')).healthName ||'',
					userId: localStorage.getItem('userInfo') && JSON.parse(localStorage.getItem('userInfo')).userId || '',
					userName: localStorage.getItem('userInfo') && JSON.parse(localStorage.getItem('userInfo')).realName || '',
				}
				if(_this.id) {
					record.id = Number(_this.id);
					record.appUserTopicsTitleEntity.id = _this.editTid
					_this.$api.appSicknessDangeUpdate(record).then((res) => {
						uni.showToast({
							title: res.data.message,
							icon: 'none'
						})
						setTimeout(() => {
							uni.navigateTo({
								url:'/pages/futureDiseases/navigation?current=0'
							})
						},2000)
					})
				}else {
					_this.$api.appSicknessDangeAdd(record).then((res) => {
						if(res.data.returnCode == 200) {
							uni.showToast({
								title: res.data.message,
								icon: 'none'
							})
							setTimeout(() => {
								uni.navigateTo({
									url:'/pages/futureDiseases/navigation?current=0'
								})
							},2000)
						}
					})
				}
			},
			
			questionArr() {
				return new Promise((success,error)=>{
					this.$api.psychologyQuestion('ids=42').then((res)=>{
						if(res){
							this.psychologyQuestion = res.data.result[42] && res.data.result[42].adTopicsRepliesEntityList.map((a)=>{
								a.adTopicsRepliesEntityList = a.adTopicsRepliesEntityList.length > 0 && a.adTopicsRepliesEntityList.map((b)=>{b.checked = false;return b})
								return a
							})
							success(res.data.result)
						}else{
							error('')
						}
					})
				})
			},
			// 日期
			bindDateChange(e) { 
				this.start_date = e.target.value;
			},
			// 获取当前时间
			getDate(type) {
			   const date = new Date();
			   let year = date.getFullYear();
			   let month = date.getMonth() + 1;
			   let day = date.getDate();
			  
			   if (type === 'start') {
				year = year - 60;
			   } else if (type === 'end') {
				year = year + 2;
			   }
			   month = month > 9 ? month : '0' + month;;
			   day = day > 9 ? day : '0' + day;
			   return `${year}-${month}-${day}`;
			},
		}
	}
</script>

<style lang="scss" scoped>
	@import '@/static/css/monitor/accomplishment/index.scss';
	.entry {
		display: flex;
		margin:30upx 0 0 58upx;
		input {
			font-size: 30upx;
			color: #333333;
			width: 100%;
		}
		.systolicPressure {
			width: 148upx;
		}
		.diastolicPressure {
			margin-left: 60upx;
			flex: 1;
		}
	}
</style>
